<?php
$application = 'application';
$modules = 'modules';
$system = 'system';
define('DOCROOT', realpath(dirname(__FILE__)).DIRECTORY_SEPARATOR);
// Make the application relative to the docroot, for symlink'd index.php
if ( ! is_dir($application) AND is_dir(DOCROOT.$application))
	$application = DOCROOT.$application;
// Make the modules relative to the docroot, for symlink'd index.php
if ( ! is_dir($modules) AND is_dir(DOCROOT.$modules))
	$modules = DOCROOT.$modules;
// Make the system relative to the docroot, for symlink'd index.php
if ( ! is_dir($system) AND is_dir(DOCROOT.$system))
	$system = DOCROOT.$system;
// Define the absolute paths for configured directories
define('APPPATH', realpath($application).DIRECTORY_SEPARATOR);
define('MODPATH', realpath($modules).DIRECTORY_SEPARATOR);
define('SYSPATH', realpath($system).DIRECTORY_SEPARATOR);
if (!function_exists('get')){//按键取数组值
	function get($a,$k){
		if (isset($a[$k])) return $a[$k];
		return null;
	}
}

function error_handler($code, $error, $file = NULL, $line = NULL){
	throw new ErrorException($error, $code, 0, $file, $line);
}
function __404(Exception $e){
	echo $error = date("Y-m-d H:i:s ").$e->getMessage().' in '.$e->getFile().' line '.$e->getLine();
}
set_exception_handler('__404');
set_error_handler('error_handler');

date_default_timezone_set('Asia/Shanghai');
include_once APPPATH.'classes/mon.php';
include_once APPPATH.'classes/common.php';
include_once APPPATH.'classes/lib/file.php';
include_once APPPATH.'classes/model/tag.php';
$mongo_config = include APPPATH.'config/conndb.php';
$conn = MON::connect($mongo_config);
$tag_model = new Model_tag();
$push_log = lib_file::instance(DOCROOT.'autopublish_push_log');
$error_log = lib_file::instance(DOCROOT.'autopublish_error_log');

$num = rand(1,3);//	!--一次发布文章数--!

$count = MON::factory('todo')->find()->count();
$array = array_fill(1,$count,true);
$positions = (array)array_rand($array,$num);
//var_dump($count,$positions);

$r = array();
foreach ($positions as $position){
	$r[] = get(MON::as_array(MON::factory('todo')->find()->skip($position)->limit(1)),0);
}
//var_dump($r);

ob_start();
foreach ($r as $k=>$todo){
	try {
		$a = array(
			'title'=>$todo['title'],
			'rewrite'=>$todo['title'],
			'keywords'=>$todo['keywords'],
			'description'=>$todo['description'],
			'content'=>htmlspecialchars_decode($todo['content']),
			'addTime'=>mt_rand(strtotime('-1 day'),time())
		);
		MON::factory('article')->insert($a);
		if ($a['_id'])
			$tag_model->tag_born($a['_id']);
		$push_log->write_line(date("Y-m-d H:i:s ").'_id: '.$a['_id'].' '.$a['title']);
		MON::factory('todo_done')->insert($todo);
		MON::factory('todo')->remove(array('_id'=>new MongoId((string)$todo['_id'])));
	} catch (Exception $e) {
		$error = date("Y-m-d H:i:s ").$e->getMessage().' in '.$e->getFile().' line '.$e->getLine();
		$error_log->write_line($error);
		continue;
	}
}
ob_end_clean();

print "publish OK\n\r";
